package com.jd.header;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import com.jd.header.adapter.PhotoAdapter;
import com.jd.header.config.ApiConfig;
import com.jd.header.databinding.ActivityMainBinding;
import com.jd.header.entity.PhotoEntity;
import com.jd.header.http.RxhttpUtil;
import com.jd.header.util.DragSelectTouchListener;
import com.jd.header.util.DragSelectionProcessor;
import com.jd.header.util.ILog;
import com.jd.header.util.JsonUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private DragSelectionProcessor.Mode mMode = DragSelectionProcessor.Mode.FirstItemDependentToggleAndUndo;
    private DragSelectTouchListener mDragSelectTouchListener;
    private DragSelectionProcessor mDragSelectionProcessor;

    private ActivityMainBinding mainBinding;
    private PhotoAdapter photoAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mainBinding.getRoot());
        RxhttpUtil.init(true);
        initView();
        initData();
        initLister();
    }

    private void initView() {
        photoAdapter = new PhotoAdapter();
        mainBinding.recyclerView.setHasFixedSize(true);
        mainBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false));
        mainBinding.recyclerView.setAdapter(photoAdapter);

        mDragSelectionProcessor = new DragSelectionProcessor(new DragSelectionProcessor.ISelectionHandler() {
            @Override
            public HashSet<Integer> getSelection() {
                return photoAdapter.getSelectMap();
            }

            @Override
            public boolean isSelected(int index) {
                return photoAdapter.getSelectMap().contains(index);
            }

            @Override
            public void updateSelection(int start, int end, boolean isSelected, boolean calledFromOnStart) {
                photoAdapter.selectRange(start, end, isSelected);
            }
        }).withMode(mMode);
        mDragSelectTouchListener = new DragSelectTouchListener(this)
                .withSelectListener(mDragSelectionProcessor);
        updateSelectionListener();
        mainBinding.recyclerView.addOnItemTouchListener(mDragSelectTouchListener);
    }

    private void updateSelectionListener() {
        mDragSelectionProcessor.withMode(mMode);
    }

    private void initData() {
        RxhttpUtil.getInstance().get(ApiConfig.getApi(), this, new RxhttpUtil.RxHttpCallBack() {
            @Override
            public void onStart() {
                ILog.e("开始请求...");
            }

            @Override
            public void onSuccess(String response) {
                PhotoEntity photoEntity = (PhotoEntity) JsonUtil.fromJson(response, new PhotoEntity());
                List<PhotoEntity.ResBean.VerticalBean> verticalBeans = new ArrayList<>(photoEntity.getRes().getVertical());
                photoAdapter.setNewInstance(verticalBeans);
                ILog.e("请求结束 " + photoAdapter.getItemCount());
            }

            @Override
            public void onError(String error) {
                ILog.e("请求异常 " + error);
            }

            @Override
            public void onFinish() {
                ILog.e("请求结束...");
            }
        });
    }

    /**
     * 每次手指按下记录的position
     */
    private int downPos = -1;

    /**
     * true开启多选  false禁止多选
     */
    public boolean isOpen = false;

    @SuppressLint("ClickableViewAccessibility")
    private void initLister() {
        mainBinding.recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (!isOpen) {
                    return false;
                }

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    downPos = -1;
                    isOpen = false;
                    ILog.e("离开屏幕事件");
                    return false;
                }

                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
                    if (downPos == -1) {
                        downPos = findItem((int) event.getX(), (int) event.getY());
                        mDragSelectTouchListener.startDragSelection(downPos);
                    }
                }
                return false;
            }
        });
    }

    private float downX, downY;
    private final float SLIDE_ANGLE = 45;
    private boolean isSlideTop;//是否是水平滑动
    private boolean isSlideLeft;//是否是水平滑动

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = ev.getX();
                downY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                float moveX = ev.getX();
                float moveY = ev.getY();
                float xDiff = Math.abs(moveX - downX);
                float yDiff = Math.abs(moveY - downY);
                double squareRoot = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
                //滑动的角度
                int yAngle = Math.round((float) (Math.asin(yDiff / squareRoot) / Math.PI * 180));
                int xAngle = Math.round((float) (Math.asin(xDiff / squareRoot) / Math.PI * 180));
                boolean isMeetSlidingYAngle = yAngle > SLIDE_ANGLE;//滑动角度是否大于45du
                boolean isMeetSlidingXAngle = xAngle > SLIDE_ANGLE;//滑动角度是否大于45du
                boolean isSlideUp = moveY < downY && isMeetSlidingYAngle;
                boolean isSlideDown = moveY > downY && isMeetSlidingYAngle;
                boolean isLeft = moveX < downX && isMeetSlidingXAngle;
                boolean isRight = moveX > downX && isMeetSlidingXAngle;
                if (isSlideUp) {
                    isSlideTop = true;
                } else if (isSlideDown) {
                    isSlideTop = false;
                } else if (isLeft) {
                    isSlideLeft = true;
                    if (!isOpen) {
                        isOpen = true;
                    }
                } else if (isRight) {
                    isSlideLeft = false;
                    if (!isOpen) {
                        isOpen = true;
                    }
                }
                downX = ev.getX();
                downY = ev.getY();
        }
        return super.dispatchTouchEvent(ev);
    }

    public int findItem(int x, int y) {
        View childViewUnder = mainBinding.recyclerView.findChildViewUnder(x, y);
        if (childViewUnder != null) {
            RecyclerView.ViewHolder childViewHolder = mainBinding.recyclerView.getChildViewHolder(childViewUnder);
            if (childViewHolder != null) {
                return childViewHolder.getPosition();
            }
        }
        return -1;
    }
}